import 'package:flutter/material.dart';
import 'package:happy_elf_app/apis/home.dart';
import 'package:happy_elf_app/store/config.dart';
import 'package:happy_elf_app/store/home.dart';
import 'package:happy_elf_app/store/user.dart';
import 'package:happy_elf_app/utils/globalKey.dart';

class Recently extends StatefulWidget {
  const Recently({super.key});

  @override
  State<Recently> createState() => _RecentlyState();
}

final UserDataProvider = Provider.of<UserData>(
  Global.navigatorKey.currentContext!,
  listen: false,
);
final HomeDataProvider = Provider.of<HomeData>(
  Global.navigatorKey.currentContext!,
  listen: false,
);

class _RecentlyState extends State<Recently>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  // List statusList =[
  //   ''
  // ];
  // 模拟接口返回的最近5周情绪数据
  List weekData = [
    // {
    //   'week': '第一周',
    //   'score': 16,
    //   'status': '中度负面情绪',
    //   'suggestion': '建议预约心理医生治疗',
    //   'isHighlight': false
    // },
    // {
    //   'week': '第二周',
    //   'score': 8,
    //   'status': '轻度负面情绪',
    //   'suggestion': '',
    //   'isHighlight': false
    // },
    // {
    //   'week': '第三周',
    //   'score': 4,
    //   'status': '无负面情绪',
    //   'suggestion': '',
    //   'isHighlight': true
    // },
    // {
    //   'week': '第四周',
    //   'score': 2,
    //   'status': '拥有积极情绪',
    //   'suggestion': '',
    //   'isHighlight': true
    // },
    // {
    //   'week': '第五周',
    //   'score': 0,
    //   'status': '情绪状态良好',
    //   'suggestion': '',
    //   'isHighlight': false
    // },
  ];

  @override
  void initState() {
    super.initState();
    getDataList();
    _controller = AnimationController(vsync: this);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  int calculateTotalScore(scores) {
    // 使用fold方法更简洁地累加（初始值0，依次加每个value）
    return scores.values.fold(0, (sum, value) => sum + value);
  }

  void getDataList() async {
    print('UserDataProvider.userData--${UserDataProvider.userData}');
    String id = HomeDataProvider.target['id'].toString();
    var res = await Home().getReportList(id);
    if (res['code'] == 200) {
      // weekData = res['data'];
      for (var item in res['data']) {
        int score = calculateTotalScore(item['data']);
        String status = '';
        String suggestion = '';
        bool isHighlight = false;
        if (score <= 4) {
          status = '正常情绪';
        } else if (score <= 9) {
          status = '轻度负面情绪';
        } else if (score <= 14) {
          status = '中轻度负面情绪';
        } else if (score <= 19) {
          status = '中重度负面情绪';
          suggestion = '建议预约心理医生治疗';
          isHighlight = true;
        } else if (score >= 20) {
          status = '重度负面情绪';
          isHighlight = true;
          suggestion = '强烈建议心理医生治疗';
        }
        weekData.add({
          'week': '第${item['weekNo']}周',
          'score': score,
          'status': status,
          'suggestion': suggestion,
          'isHighlight': isHighlight
        });
      }
      setState(() {});
    }
  }

  Widget itemBuild(data) {
    print('data$data');
    return Container(
      margin: const EdgeInsets.symmetric(
          horizontal: 16, vertical: 8), // 垂直间距调整为8，减少拥挤感
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.2), // 阴影减弱，更精致
            blurRadius: 6,
            offset: const Offset(0, 2), // 阴影下移，增强立体感
          ),
        ],
        // 高亮项添加边框
        border: data['isHighlight']
            ? Border.all(color: Colors.red.withOpacity(0.3), width: 1)
            : null,
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(width: 10),
          // 圆形数字标记
          Container(
            width: 64,
            height: 64,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              // 高亮项添加背景色
              color: data['isHighlight']
                  ? Colors.red.withOpacity(0.05)
                  : Colors.transparent,
              border: Border.all(
                color: data['isHighlight'] ? Colors.red : Colors.grey[300]!,
                width: 4,
              ),
            ),
            child: Center(
              child: Text(
                '${data['score']}',
                style: TextStyle(
                  fontSize: 30,
                  fontWeight: FontWeight.bold,
                  color: data['isHighlight'] ? Colors.red : Colors.grey[600],
                ),
              ),
            ),
          ),
          const SizedBox(width: 26),
          Text(
            data['week'],
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600, // 加粗提升标题层级
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(width: 26),

          // 周次和情绪状态
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min, // 避免Column无限增高
              children: [
                Text(
                  data['status'],
                  style: TextStyle(
                      fontSize: 14,
                      color: Color.fromRGBO(0, 0, 0, 1) // 高亮项状态文字变红
                      ),
                ),
                if (data['suggestion'].isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.only(top: 4), // 增加建议文本的上边距
                    child: Text(
                      data['suggestion'],
                      style: const TextStyle(
                        fontSize: 13, // 建议文本稍小
                        color: Colors.red,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
              ],
            ),
          ),
          // // 高亮项添加右侧指示图标
          // if (data['isHighlight'])
          //   const Icon(
          //     Icons.arrow_forward_ios,
          //     color: Colors.red,
          //     size: 16,
          //   )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 540, // 固定高度
      margin: const EdgeInsets.only(bottom: 16),
      child: SingleChildScrollView(
        // 移除滚动到边缘的水波纹效果
        physics: const ClampingScrollPhysics(),
        child: Column(
          // 内容顶部添加标题
          children: [
            const Padding(
              padding: EdgeInsets.only(top: 16, bottom: 8),
              child: Text(
                '最近情绪记录',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF333333),
                ),
              ),
            ),
            if (weekData.isNotEmpty)
              ...weekData.map((e) => itemBuild(e)).toList(),
            const SizedBox(height: 16), // 底部留白，避免最后一项被遮挡
          ],
        ),
      ),
    );
  }
}
